<?php 
include 'db_config.php';

define("TOKEN", "fqm123"); 

$_TIME = time(); 

// globar
$TABLE_OPENID = "client_wechat_openid";

$wechatObj = new wechatCallbackapi(); 

//$wechatObj->valid();//验证完成后可将此行代码注释掉 

$wechatObj->handle(); 
   
class wechatCallbackapi
{ 
    private $openID   = null;

    private $serverID = null;

    private $isBinded = null;

    // 接口验证
    public function valid() 
    { 
        $echoStr = $_GET["echostr"]; 
   
        //valid signature , option 
        if($this->checkSignature()){ 
            echo $echoStr; 
            exit; 
        } 
    } 
   
    // 判断是否已经绑定
    private function _isBinded($openID){
        $result = mysql_query("SELECT COUNT(*) as count FROM clients WHERE $TABLE_OPENID = '$openID';");
        while($row = mysql_fetch_array($result)) {
            if($row['count'] > 0)
                return true;
        }
        return false;
    }

    // 向客户端发送文本
    public function responseText($contentStr){

        $textTpl = "<xml> 
                    <ToUserName><![CDATA[%s]]></ToUserName> 
                    <FromUserName><![CDATA[%s]]></FromUserName> 
                    <CreateTime>%s</CreateTime> 
                    <MsgType><![CDATA[%s]]></MsgType> 
                    <Content><![CDATA[%s]]></Content> 
                    <FuncFlag>0</FuncFlag> 
                    </xml>";          

        echo sprintf($textTpl, $this->openID, $this->serverID, $_TIME, "text", $contentStr); 
    }

    // 按钮事件处理入口
    public function responseEvent($postObj){
        if(preg_match("/mvip/is", $postObj->EventKey)){
           if(!$this->isBinded){
                $this->responseText("你还未绑定会员卡\n请发送bd + 手机号码进行绑定。");
                return false;
           }
        }

        switch ($postObj->EventKey) {
                   // 交易明细
                   case 'MVIP-TDETAIL':
                        $detail_tpl = "<xml>
                        <ToUserName><![CDATA[%s]]></ToUserName>
                        <FromUserName><![CDATA[%s]]></FromUserName>
                        <CreateTime>%s</CreateTime>
                        <MsgType><![CDATA[link]]></MsgType>
                        <Title><![CDATA[title1]]></Title> 
                        <Description><![CDATA[description1]]></Description>
                        <Url><![CDATA[www.baidu.com]]></Url>
                        <MsgId>1</MsgId>
                        </xml>";
                        echo sprintf($detail_tpl, $this->openID, $this->serverID, $_TIME);
                        break;
                   // 我的积分
                   case 'MVIP-CREDIT':                        
                        break;
                   // 卡内余额
                   case 'MVIP-ACCOUNT':
                        $rst = mysql_query("SELECT client_money,client_credit FROM clients WHERE $TABLE_OPENID = '$this->openID';");
                        $rst = mysql_fetch_array($rst);
                        $this->responseText("尊敬的会员\n您当前余额" . $rst['client_money'] . "元。\n" . "您当前积分" . $rst['client_credit'] . "。");
                        break;
               }       
    }


    // 普通文本处理接口
    public function TextRequest($Content){
        // 绑定text请求
        if(preg_match("/bd[ |\+]{0,}\d{11}/", $Content) && !$this->isBinded){
            $phone = preg_replace("/bd[ |\+]{0,}/", '', $Content);
            if(!preg_match("/\d{11}/", $Content)){
                $this->responseText("请输入正确的手机号码!");
            } else {
                $_SQL = "UPDATE clients SET $TABLE_OPENID = '$this->openID' WHERE client_phone = $phone;";
                $rst = mysql_query($_SQL);
                if($rst !== FALSE){
                    $this->responseText("绑定成功，享受微信带来的便捷吧!");
                } else {
                    $this->responseText("绑定失败，技术人员将尽快修复!");
                }
            }
        }

        // 获取openid请求
        if(preg_match("/getopenid/", $Content)){
            $this->responseText($this->openID);
            file_put_contents('openid', $this->openID);
        }
    }

    // 主入口
    public function handle() 
    {
        //get post data, May be due to the different environments 
        $postStr = $GLOBALS["HTTP_RAW_POST_DATA"]; 
        $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA); 

        // 记录openid
        $this->openID = $postObj->FromUserName; 
        // 记录服务号ID
        $this->serverID = $postObj->ToUserName;
        // 记录是否已经绑定账号
        $this->isBinded = $this->_isBinded($this->openID);

        //extract post data 
        if (!empty($postStr)){  
            $time = time(); 
            switch($postObj->MsgType){
                case "text" :
                    $this->TextRequest($postObj->Content);
                    break;
                case "event" :
                    $this->responseEvent($postObj);
                    break;
            }
        }
    } 
           
    private function checkSignature() 
    { 
        $signature = $_GET["signature"]; 
        $timestamp = $_GET["timestamp"]; 
        $nonce = $_GET["nonce"];     
                   
        $token = TOKEN; 
        $tmpArr = array($token, $timestamp, $nonce); 
        sort($tmpArr); 
        $tmpStr = implode( $tmpArr ); 
        $tmpStr = sha1( $tmpStr ); 
           
        if( $tmpStr == $signature ){ 
            return true; 
        }else{ 
            return false; 
        } 
    } 
} 